<template>
  <div class="container">
    <el-divider content-position="left"><span class="title-left-color">基本信息</span></el-divider>
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="场景：" prop="category_scenario_key">
            <el-select v-model.trim="form.category_scenario_key" placeholder="场景" @change="handleChangeCategory">
              <el-option v-for="item in selectMap" :label="item.dictLabel" :value="item.dictValue" :key="item.id"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="问题分类：" prop="category_id">
            <el-select v-model.trim="form.category_id" placeholder="问题分类">
              <el-option v-for="item in problemClassSelectFormList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" plain @click="handleFaqCategoryRefresh">刷新</el-button>
        </el-col>
        <el-col :span="12">
          <el-form-item label="问题名称：" prop="question">
            <el-input v-model="form.question" placeholder="问题名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序：" prop="sort">
            <el-input v-model.trim="form.sort" placeholder="排序"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="回答：" prop="answer">
            <el-input v-model.trim="form.answer" type="textarea" :rows="4" placeholder="回答"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { postOrPutType } from "@/constants";
import type { ViewMode } from "@/types/common";
import { useState } from "@/hooks/useState.ts";
import type { IDictData } from "@/types/dict";
import type { IFaqCategory } from "@/types/problemManage/faqCategory";
import type { IFaq } from "@/types/problemManage/faq";
import { commonFaqInfo } from "@/utils/api/faq";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  selectMap: Array<IDictData>;
  problemClassAllList: Array<IFaqCategory>;
}
const { selectMap, problemClassAllList } = defineProps<Props>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });
const form = defineModel<IFaq>("form", { required: true });
const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
  handleFaqCategoryRefresh: [];
}>();

const isDisabledbtn = ref(false);
const formRef = useTemplateRef("formRef");
const methodType = ref<postOrPutType>("PUT");
const problemClassSelectFormList = ref<Array<IFaqCategory>>([]);
const rules = reactive({
  category_scenario_key: [{ required: true, message: "请选择场景值", trigger: "blur" }],
  question: [{ required: true, message: "请填写问题名称", trigger: "blur" }],
  answer: [{ required: true, message: "请填写回答信息", trigger: "blur" }],
  category_id: [{ required: true, message: "请选择问题分类", trigger: "blur" }],
  sort: [{ required: true, message: "请填写排序", trigger: "blur" }]
});

onMounted(() => {
  console.log("Component mounted!");
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});

/*  */
watch(
  () => form.value.id,
  newValue => {
    if (newValue == 0) {
      /* 初始化数据 */
    } else {
      /* 执行了 */
      console.log("form.category_id", form.value.category_id);
      handleFilterProblemClass(form.value.category_scenario_key);
    }
  }
);

/* 刷新问题分类 */
function handleFaqCategoryRefresh() {
  emit("handleFaqCategoryRefresh");
}

/* 初始化数据 */
function handleInitData() {
  methodType.value = "POST";
  isDisabledbtn.value = false;

  formRef.value?.resetFields();
  formRef.value?.clearValidate();
}
/* 场景change事件 */
function handleChangeCategory(data: string) {
  handleFilterProblemClass(data);
  form.value.category_id = "";
}

/* 过滤问题分类 */
function handleFilterProblemClass(data: string) {
  problemClassSelectFormList.value = problemClassAllList.filter(item => item.scenario == data);
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  /* 防止多次提交 */
  toggleState(true);
  commonFaqInfo(form.value, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      cancelSubmit();
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  // clearData();
  // activeName = "one";
  emit("handleInitData");
}
</script>

<style lang="scss" scoped>
/* 修改select的盒模型 */
.el-select {
  display: block;
}
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}
</style>
